import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { Message } from 'element-ui'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(function(config) {
  const token = store.state.user.token
  if (token) {
    const currentTime = Date.now()
    const startTime = localStorage.getItem('logTime')
    const waitTime = 2000 * 60 * 60
    if (currentTime - startTime > waitTime) {
      store.commit('user/logout')
      router.push('/login')
    }
    config.headers.Authorization = 'Bearer ' + token
  }
  return config
}, function(error) {
  return Promise.reject(error)
})
// 响应拦截器
service.interceptors.response.use(res => {
  if (res.data.success) {
    // 操作成功
    return res.data.data
  } else {
    // 如果success为false 业务出错,直接触发reject
    // 被catch分支捕获
    // 弹出错误提示框
    Message.error(res.data.message)
    // Promise.reject()阻断请求，也就是说请求后的内容不让执行了
    return Promise.reject(res.data.message)
  }
}, (err) => {
  // token失效被动处理
  if (err.response && err.response.data.code === 10002) {
    store.commit('user/logout')
    router.push('/login')
  }
  // 弹出错误提示框
  Message.error('系统错误')
  return Promise.reject('系统错误')
})
export default service
